<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="addRule">增加停车计费规则</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上线(元)" prop="chargeCeiling">
          <template #default="obj">
            {{ obj.row.chargeCeiling?obj.row.chargeCeiling:"---" }}
          </template>
        </el-table-column>
        <el-table-column label="计费方式" prop="chargeType" :formatter="formatter" />
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button size="mini" type="text" @click="editRule(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delRule(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="page-container">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :current-page="params.page"
          :page-size="params.pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 弹框 -->
    <el-dialog :visible="dialogVisible" width="700px" title="新增规则" @close="closeDialog">
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="top">
          <el-form-item label="计费规则编号" prop="ruleNumber">
            <el-input v-model="addForm.ruleNumber" />
          </el-form-item>
          <el-form-item label="计费规则名称" prop="ruleName">
            <el-input v-model="addForm.ruleName" />
          </el-form-item>
          <el-form-item label="计费方式" prop="chargeType">
            <el-radio-group v-model="addForm.chargeType" size="small">
              <el-radio label="duration" border>时长收费</el-radio>
              <el-radio label="turn" border>按次收费</el-radio>
              <el-radio label="partition" border>分段收费</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="flex-container" style="display:flex;justify-content:space-between">
            <el-form-item label="免费时长">
              <el-input v-model="addForm.freeDuration" />
            </el-form-item>
            <el-form-item label="收费上限">
              <el-input v-model="addForm.chargeCeiling" />
            </el-form-item>
          </div>
          <el-form-item label="计费规则">
            <!-- 按时长收费区域 -->
            <div v-if="addForm.chargeType==='duration'" class="duration" style="display:flex">
              每<el-input v-model="addForm.durationTime" class="input-box" />
              <el-select v-model="addForm.durationType" class="select-time">
                <el-option
                  v-for="item in durationTypeList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>

              <el-input v-model="addForm.durationPrice" class="input-box" /> 元
            </div>
            <!-- 按次收费区域 -->
            <div v-if="addForm.chargeType==='turn'" class="turn" style="display:flex">
              每次<el-input v-model="addForm.turnPrice" class="input-box" style="width:150px" /> 元
            </div>
            <!-- 按分段收费区域 -->
            <div v-if="addForm.chargeType==='partition'" class="partition">
              <div class="item" style="display:flex">
                <el-input v-model="addForm.partitionFrameTime" class="input-box" style="width:100px" />
                小时内,每小时收费
                <el-input v-model="addForm.partitionFramePrice" class="input-box" style="width:100px" />
                元
              </div>
              <div class="item" style="display:flex;margin:30px auto 0">
                每增加
                <el-input v-model="addForm.partitionIncreaseTime" class="input-box" style="width:120px;" />
                小时,增加
                <el-input v-model="addForm.partitionIncreasePrice" class="input-box" style="width:120px;" />
                元
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addComfire">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { utils, writeFileXLSX } from 'xlsx'
import { getRuleListAPI, createRuleAPI, DelRuleAPI, EditRuleAPI, DetailRuleAPI } from '@/api/rule'
export default {
  name: 'Building',
  data() {
    return {
      params: {
        page: 1,
        pageSize: 2
      },
      durationTypeList: [
        {
          id: 'hour',
          name: '小时'
        },
        {
          id: 'minute',
          name: '分钟'
        }
      ],
      ruleList: [],
      total: 0,
      // 添加计费的显示和隐藏
      dialogVisible: false,
      addForm: {
        ruleNumber: '', // 计费规则编号
        ruleName: '', // 计费规则名称
        chargeType: 'duration', // 计费规则类型 duration / turn / partition
        chargeCeiling: null,
        freeDuration: null,
        // 时长计费独有字段
        durationTime: null, // 时长计费单位时间
        durationPrice: null, // 时长计费单位价格
        durationType: 'hour',
        // 按次收费独有字段
        turnPrice: null,
        // 分段计费独有字段
        partitionFrameTime: null, // 段内时间
        partitionFramePrice: null, // 段内费用
        partitionIncreaseTime: null, // 超出时间
        partitionIncreasePrice: null // 超出费为收费价钱

      }, // 计费规则表单对象
      addFormRules: {
        ruleNumber: [{ required: true, message: '请输入规则编号', trigger: 'blur' }],
        ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
        chargeType: [{ required: true, message: '请选择收费类型', trigger: 'blur' }]
      } // 计费规则校验规则对象
    }
  },
  created() {
    // 获取规则列表
    this.getRuleList()
  },
  methods: {
    // 获取规则列表
    async getRuleList() {
      const res = await getRuleListAPI(this.params)
      console.log(res)
      this.total = res.data.total
      this.ruleList = res.data.rows
    },
    // 格式化输出
    formatter(row) {
      const chargeType = row.chargeType
      const Mapping = {
        duration: '时长收费',
        turn: '按次收费',
        partition: '分段收费'
      }
      return Mapping[chargeType]
    },
    // 处理分页
    handleCurrentChange(page) {
      this.params.page = page
      this.getRuleList()
    },
    // 导出excel
    async exportToExcel() {
      const Mapping = {
        duration: '时长收费',
        turn: '按次收费',
        partition: '分段收费'
      }
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 创建一个工作表 要求一个对象数组格式
      // 表头英文字段key
      const tableHeaderKeys = ['ruleNumber', 'ruleName', 'freeDuration', 'chargeCeiling', 'chargeType', 'ruleNameView']
      // 表头中文字段value
      const tableHeaderValues = ['计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上线(元)', '计费方式', '计费规则']
      const res = await getRuleListAPI(this.params)
      console.log(res)
      const sheetData = res.data.rows.map(item => {
        const obj = {}
        tableHeaderKeys.forEach(key => {
          // 判断计费方式在里面，如果在里面就通过映射的方式将英文改成中文
          if (item[key] in Mapping) {
            item[key] = Mapping[item[key]]
          }
          obj[key] = item[key]
        })
        return obj
      })
      console.log(sheetData)
      const worksheet = utils.json_to_sheet(

        sheetData

      )

      // 把工作表添加到工作簿  Data为工作表名称
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      // 导出方法进行导出
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    },
    // 关闭
    closeDialog() {
      this.dialogVisible = false
    },
    // 显示规则弹出框
    addRule() {
      this.dialogVisible = true
    },
    // 添加规则
    addComfire() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          // 先接口发起请求
          // 如果addForm中有id的话那么就是编辑规则
          if (this.addForm.id) {
            await EditRuleAPI(this.addForm)
          } else {
            await createRuleAPI(this.addForm)
          }

          this.$message.success(`${this.addForm.id ? '修改' : '添加'}规则成功`)
          // 自动清空form表单和手动清空
          this.addForm = []
          this.$refs.addForm.resetFields()
          this.dialogVisible = false
          this.getRuleList()
        }
      })
    },
    // 删除规则
    delRule(id) {
      // 调用删除接口
      this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await DelRuleAPI(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getRuleList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 编辑规则
    async editRule(id) {
      const res = await DetailRuleAPI(id)
      // console.log(res)
      // 回显到addForm
      this.addForm = res.data
      this.dialogVisible = true
    }

  }
}
</script>

<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
/* 弹窗整体样式 */
.form-container .el-dialog {
   font-family: "Microsoft YaHei", "Helvetica Neue", sans-serif;
   border-radius: 8px;
   box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
   overflow: hidden;
 }

 /* 弹窗标题栏 */
.form-container .el-dialog__header {
   padding: 16px 24px;
   background-color: #f5f7fa;
   border-bottom: 1px solid #e4e7ed;
 }

.form-container .el-dialog__title {
   font-size: 16px;
   font-weight: 600;
   color: #303133;
 }

 /* 表单容器 */
 .form-container {
   padding: 20px 24px;
 }

 /* 表单整体样式 */
.form-container .el-form {
   font-size: 14px;
 }

 /* 表单项样式 */
.form-container .el-form-item {
   margin-bottom: 18px;
 }

.form-container .el-form-item__label {
   font-weight: 500;
   color: #606266;
   padding-bottom: 6px;
   font-size: 14px;
 }

 /* 输入框样式 */
.form-container .el-input__inner {
   height: 36px;
   border-radius: 4px;
   border-color: #dcdfe6;
   padding: 0 12px;
   font-size: 14px;
   transition: all 0.2s;
 }

.form-container .el-input__inner:focus {
   border-color: #409eff;
   box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
   outline: none;
 }

 /* 单选按钮组 */
.form-container .el-radio-group {
   display: flex;
   gap: 15px;
   padding: 5px 0;
 }

.form-container .el-radio {
   border-radius: 4px;
   transition: all 0.2s;
 }

.form-container .el-radio__label {
   padding-left: 8px;
   color: #606266;
 }

.form-container .el-radio.is-checked .el-radio__inner {
   background-color: #409eff;
   border-color: #409eff;
 }

.form-container .el-radio.is-checked + .el-radio__label {
   color: #409eff;
 }

 /* 两列布局容器 */
.form-container .flex-container {
   gap: 20px !important;
   margin-bottom: 18px;
 }

.form-container .flex-container .el-form-item {
   flex: 1;
   margin-bottom: 0;
 }

 /* 计费规则区域通用样式 */
.form-container .duration, .turn, .partition {
   background-color: #f9f9f9;
   border-radius: 6px;
   padding: 15px;
   border: 1px solid #eee;
 }

 /* 时长收费区域 */
.form-container .duration {
   align-items: center;
   gap: 10px;
 }
.form-container

 /* 按次收费区域 */
.turn {
   align-items: center;
   gap: 20px;
   justify-content: center;

 }

 /* 分段收费区域 */
.form-container .partition {
   gap: 15px;
 }

.form-container .partition .item {
   align-items: center;
   gap: 10px;
 }

.form-container .partition .item:first-child {
   margin-bottom: 10px;
 }

.form-container .partition .item:last-child {
   margin: 10px 0 0 !important;
 }

 /* 计费规则中的输入框 */
.form-container .input-box {
   border-radius: 4px;
 }

 /* 下拉选择器 */
.form-container .el-select {
   width: 100px;
 }

.form-container .el-select .el-input__inner {
   width: 100%;
 }

 /* 弹窗底部按钮 */
.form-container .el-dialog__footer {
   padding: 12px 24px;
   background-color: #f5f7fa;
   border-top: 1px solid #e4e7ed;
   display: flex;
   justify-content: flex-end;
   gap: 10px;
 }

.form-container .el-button {
   padding: 6px 15px;
   border-radius: 4px;
   font-size: 12px;
   transition: all 0.2s;
 }

.form-container .el-button--primary {
   background-color: #409eff;
   border-color: #409eff;
 }

.form-container .el-button--primary:hover {
   background-color: #66b1ff;
   border-color: #66b1ff;
 }

.form-container .el-button:not(.el-button--primary):hover {
   background-color: #e9e9eb;
   color: #303133;
 }
.form-container  .select-time{
  width: 300px;
}
</style>
